//
// Created by dukang wang on 2025/1/4.
//

#include "../include/DataQueue.h"
#include "../AndroidLog.h"

namespace hy {

    /**
     * 初始化线程锁
     */
    DataQueue::DataQueue() {
        pthread_mutex_init(&mutexPacket, NULL);
        pthread_cond_init(&condPacket, NULL);
    }

    DataQueue::~DataQueue() {
        pthread_mutex_destroy(&mutexPacket);
        pthread_cond_destroy(&condPacket);
    }

    int DataQueue::putPcmData(PcmData *data) {
        pthread_mutex_lock(&mutexPacket);
        queuePacket.push(data);
        pthread_cond_signal(&condPacket);
        pthread_mutex_unlock(&mutexPacket);
        return 0;
    }

    PcmData *DataQueue::getPcmData() {
        pthread_mutex_lock(&mutexPacket);
        PcmData *pcmData = NULL;

        while (work && queuePacket.empty()){
            LOGE("DataQueue pcmData is null, enter waitting")
            //线程挂起等待
            pthread_cond_wait(&condPacket, &mutexPacket);
        }

        if (queuePacket.size() > 0) {
            LOGE("DataQueue pcmData size=%d", queuePacket.size())
            pcmData = queuePacket.front();
            queuePacket.pop();
        }

        pthread_mutex_unlock(&mutexPacket);
        return pcmData;
    }

    void DataQueue::setWork(int work) {
        pthread_mutex_lock(&mutexPacket);
        this->work = work;
        pthread_cond_signal(&condPacket);//唤醒等待
        pthread_mutex_unlock(&mutexPacket);
    }

    int DataQueue::clearPcmData() {
        pthread_cond_signal(&condPacket);
        pthread_mutex_lock(&mutexPacket);
        while (queuePacket.size() > 0) {
            PcmData *pcmData = queuePacket.front();
            queuePacket.pop();
            free(pcmData->getData());
            pcmData = NULL;
        }
        pthread_mutex_unlock(&mutexPacket);
        return 0;
    }

    void DataQueue::release() {
        clearPcmData();
    }

    int DataQueue::getPcmDataSize() {
        int size = 0;
        pthread_mutex_lock(&mutexPacket);
        size = queuePacket.size();
        pthread_mutex_unlock(&mutexPacket);
        return size;
    }

}
